package com.aqie.meet.ui.chat;

import android.os.Build;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSONArray;
import com.aqie.libcommon.utils.SimpleJsonTool;
import com.aqie.libfactory.Factory;
import com.aqie.libfactory.data.helper.MessageHelper;
import com.aqie.libfactory.model.api.RspModel;
import com.aqie.libfactory.model.api.chat.UnReadMessage;
import com.aqie.libfactory.model.api.websocket.SignMessageModel;
import com.aqie.libfactory.model.card.MessageCard;
import com.aqie.libfactory.model.db.Message;
import com.aqie.libfactory.model.db.User;
import com.aqie.libfactory.net.Network;
import com.aqie.libfactory.net.RemoteService;
import com.aqie.libfactory.presenter.message.ChatContract;
import com.aqie.libfactory.presenter.message.ChatUserPresenter;
import com.aqie.meet.R;
import com.aqie.meet.ui.login.AccountActivity;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ChatUserFragment extends ChatFragment<User> implements ChatContract.UserView {
    public ChatUserFragment() {}

    @BindView(R.id.chat_title)
    TextView mReceiverName;

    List<UnReadMessage> unReadMessages;
    @Override
    protected ChatContract.Presenter initPresenter() {
        return new ChatUserPresenter(this, mReceiverId);
    }

    /**
     * 对和你聊天的朋友的信息进行初始化操作
     * @param user
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onInit(User user) {
        // 设置聊天对象名称
        mReceiverName.setText(mReceiverUsername);
        // 从服务器拉取未签收消息
        unReadMsgList();

        // 进行消息签收 只签收未签收的
        // signMessages();
        // 签收完毕更新数据库状态

        // todo test 本地未读消息
        List<Message> messages = MessageHelper.findUserUnSignMessages(mReceiverId);
        Log.e("UNREAD", messages.toString());
        Log.e("UNREAD", "mReceiverId: " + mReceiverId);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void signMessages() {
        List<Message> messages = MessageHelper.findUserUnSignMessages(mReceiverId);
        if(messages.size() > 0){
            // String rspString = SimpleJsonTool.toJson(messages);
            Log.e("UNREAD", messages.toString());

            String collect = messages.stream().map(Message::getMsgId).collect(Collectors.joining(","));
            SignMessageModel signMessageModel = new SignMessageModel();
            signMessageModel.setExpand(collect);
            WebSocketManager manager = WebSocketHandler.getDefault();
            manager.send(JSONArray.toJSON(signMessageModel).toString());
            Log.e(TAG,"消息签收完毕 " + collect);
            Log.e(TAG, JSONArray.toJSON(signMessageModel).toString());
            // BaseApplication.showToast("消息签收完毕");
        } else {
            // 已经在点击时候更新了
            // 更新对应session 未读消息为0 这里传receiverId 是对的
            // SessionHelper.updateUnReadNumber(mReceiverId);
            // BaseApplication.showToast(mReceiverId + "本地数据库无需要签收消息");
        }

    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private void unReadMsgList() {
        RemoteService service = Network.remote();
        Call<RspModel<List<UnReadMessage>>> call = service.unReadMsgList();
        call.enqueue(new Callback<RspModel<List<UnReadMessage>>>() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call<RspModel<List<UnReadMessage>>> call, Response<RspModel<List<UnReadMessage>>> response) {
                RspModel<List<UnReadMessage>> body = response.body();

                if(response.code() == 401){
                    Log.e(TAG, "尚未登录");
                    AccountActivity.show(getContext());
                    return;
                }
                if(body !=null && body.success()){
                    // BaseApplication.showToast("拉取未读消息成功");
                    unReadMessages = body.getData();
                    String rspString = SimpleJsonTool.toJson(unReadMessages); Log.e(TAG, rspString);
                    // 进行消息派发
                    List<MessageCard> cardsList = new ArrayList<>();
                    unReadMessages.forEach((item) -> {
                        MessageCard card = new MessageCard();
                        card.setMsg(item.getMsg());
                        card.setMsgId(item.getId());
                        card.setReceiverId(item.getReceiverId());
                        card.setSenderId(item.getSenderId());
                        card.setSign(1);
                        try {
                            card.setCreateAt(sdf.parse(item.getCreateTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        cardsList.add(card);
                    });

                    MessageCard[] cards = cardsList.toArray(new MessageCard[0]);
                    if(cards.length > 0){
                        Factory.getMessageCenter().dispatch(cards);
                        // 进行消息签收 只签收未签收的
                        signMessages();
                    } else {
                        // BaseApplication.showToast("无未读消息");
                    }

                }
            }

            @Override
            public void onFailure(Call<RspModel<List<UnReadMessage>>> call, Throwable t) {

            }
        });
    }
}